<?php
Namespace Cyfy\Modules\Forms;

use \Cyfy\Message;
use \Cyfy\Modules\Forms\Module;

/**
 * Creates a new fileupload element.
 *
 * Usage:
 * <code>
 * // called in method structure() of a form, that's why there is $this
 *
 * $i = new Forms\File("image2", "Upload Image", "dir/to/be/uploadedTo", 0, 0, array("jpg", "png", "gif"));
 * $i -> filetypesDescription = "Images";
 * $i -> maxFiles = 1;
 * $i -> customFilenames = array($imageName); // array of custom filenames
 * $this -> AddItem($i);
 *
 * </code>
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
 
class File extends Input
{
    /** 
     * Path for the file to be uploaded.
     * @var string
     */
    public $whereToUpload = '';
    
    /**
     * Maxfilesize in bytes. If 0, it's "unlimited".
     * @var int
     */
    public $maxFileSize = 0;
    
    /**
     * Minimum number of files to be uploaded.
     * @var int
     */
    public $minFiles = 1;
    
    /**
     * Maximum number of files to be uploaded.
     * @var int
     */
    public $maxFiles = 1;
    
    /** 
     * Real filenames of uploaded files. The files can be renamed when uploading.
     * @var array
     */
    public $files = array();
    
    /** 
     * Original filenames.
     * @var array
     */
    public $filesOriginal = array();
    
    /** 
     * Custon filenames, which can replace given names. The length of this array must be at least high as number of uploaded files.
     * @var array
     */
    public $customFilenames = array();
    
    /**
     * Filetypes, which can be uploaded. Array of extensions - see class description for example.
     * @var array
     */
    public $fileTypes = array();
    
    /**
     * Description shown in browser when selecting files.
     * @var string
     */
    public $filetypesDescription = "All files";
    
    /**
     * Upload directory is selected in the form itself.
     * @var string
     */
    public $dirnameFromInput = "";
    
    /**
     * Creates a new fileupload element.
     * @param string Name of the element.
     * @param string Title shown next to the form.
     * @param string Where the files will be uploaded. Can be followed by $dirnameFromInput.
     * @param int Maximum filesize in bytes.
     * @param int Number of files. This will set both mininum and maximum for files.
     * @param array Filetypes to be used. See example in class description.
     */
    function __construct($name, $title, $whereToUpload, $maxFileSize = 0, $numberOfFiles = 1, $filetypes = array("*"))
    {
        $this -> name = $name;
        $this -> title = $title;
        $this -> whereToUpload = $whereToUpload;
        $this -> maxFileSize = $maxFileSize;
        $this -> filetypes = $filetypes;
        $this -> minFiles = $numberOfFiles;
        $this -> maxFiles = $numberOfFiles;
        $this -> filetypesDescription = Module :: t(100);
    }
    
    /**
     * Sets $dirnameFromInput
     * @param string Path, without ending forward slash.
     */
    function appendDirnameFromInput($inputname)
    {
        $this -> dirnameFromInput = $inputname;
    }
    
    /**
     * Serialization of file uploading.
     * @return string HTML content
     */
    function __toString()
    {
        // file settings
        $id = "fileUpload" . uniqid();
        \Cyfy\Modules\jquery\Plugins :: load("jquerySWFUpload");	
        
        // more files or just one
        $selectMethod = ($this -> maxFiles > 1) ? "SELECT_FILES" : "SELECT_FILE";
        
        $types = "";
        foreach($this -> filetypes as $type)
        {
            $types .= "*." . $type . ";";
        }
        $types = substr($types, 0, -1);
        $style = "";
        $finished = Module :: t(110);
        $loaded = Module :: t(120);
        $bytes = Module :: t(130);
        $fileFail = Module :: t(230);
        $session = session_id();
        $lang = \Cyfy\Language :: getActive();
        // file JS
        $js = <<<JAVASCRIPT
$(document).ready(function(){
$('#{$id}').swfupload({
    upload_url: Cyfy.getSourcePath("call.php?module=jquerySWFUpload&call=upload"),
    file_size_limit : "{$this -> maxFileSize}",
    file_types : "{$types}",
    file_types_description : "{$this -> filetypesDescription}",
    file_upload_limit : "0",
    flash_url : swfUploadDir + "swfupload.swf",
    button_image_url : Cyfy.getSourcePath("Cyfy/Modules/jquerySWFUpload/buttons/{$lang}.png"),
    button_width : 93,
    button_height : 28,
    button_cursor: SWFUpload.CURSOR.HAND,
    button_window_mode :  SWFUpload.WINDOW_MODE.TRANSPARENT,
    button_action : SWFUpload.BUTTON_ACTION.{$selectMethod},
    button_placeholder : $('#{$id}')[0],
    debug: false,
    post_params: {"PHPSESSID" : "{$session}", "customFilename" : "{$id}"}
  //  custom_settings : {cyfyLanguage : "{$lang}"}
})
    .bind('fileQueued', function(event, file){
        $(this).swfupload('startUpload');
    })
    .bind('fileQueueError', function(event, file, errorCode, message){
        alert('File queue error - '+message+'');
    })
    .bind('uploadStart', function(event, file){
        $('#form-upload-log-{$id}').append('<table style="width:100%;" class="form-file-upload-detail" id="form-file-upload-detail-' + file.id + '"><tr><td rowspan="2" class="image"></td><th class="name">' + file.name  +'</th><td rowspan="2" class="delete"></td></tr><tr><td class="state">{$loaded} <span class="bytes"></span> {$bytes}</td></tr></table>');
    })
    .bind('uploadProgress', function(event, file, bytesLoaded){
        $('#form-upload-log-{$id} #form-file-upload-detail-' + file.id + ' .bytes').html(bytesLoaded);
    })
    .bind('uploadSuccess', function(event, file, serverData){
        if(serverData != "ERROR" && serverData != "")
        {
            var filename = serverData;
            $("#form-file-upload-detail-" + file.id + " .name").html(filename);
            $("#form-file-upload-detail-" + file.id + " .delete").html('<a class="button button-warning" onclick="Cyfy.ajax(\'jquerySWFUpload\', \'deleteTemporaryFile\', \'\', \'filename={$id}'+ filename +'&originalFilename=' + filename + '\'); $(\'#{$id}' + file.id + 'Input\').remove(); $(\'#form-file-upload-detail-' + file.id + '\').fadeOut(); return false;" href="#">X</a>');
        
            var ext = getExtension(filename);
            //if(ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "gif")
            var image = "";
            if(true)
            {
                var image = '<img class="file-upload-image" src="' + Cyfy.getSourcePath('tmp/resized_{$id}' + filename) + '" //>';
            }
            
            $('#form-upload-log-{$id} #form-file-upload-detail-' + file.id + ' .image').html(image);
            $('#form-upload-log-{$id} #form-file-upload-detail-' + file.id + ' .state').html("{$finished}");
            
            // add to the form
            $('#{$id}Inputs').append('<input type="hidden" name="{$this->name}[]" id="{$id}'+ file.id +'Input" value="{$id}' + filename +'" />');
            $('#{$id}Inputs').append('<input type="hidden" name="{$this->name}Original[]" id="{$id}'+ file.id +'Original" value="' + filename +'" />');
            
        }else{
            alert('{$fileFail}\\n\\n' + file.name);
            $('#form-file-upload-detail-' + file.id).remove();
        }
    })
    .bind('uploadComplete', function(event, file)
    {
        
        $(this).swfupload('startUpload');
    })
    .bind('uploadError', function(event, file, errorCode, message){
        alert('Upload error - '+message+'');
    });

});	
    
JAVASCRIPT;
        \Cyfy\Cyfy ::  JavaScript($js, "inline", "header");

        // if description -> show popup
        $this -> loadDescription();
        
        $required = ($this->required) ? " form-validate" : "";
        $star = ($this->required) ? Module :: REQUIRED_CHAR : "";
        
        $output = "<div class=\"form-item form-item-{$this->name}\"> \n";
        $output .= "    <label class=\"form-label-{$this->name}{$required}\" title=\"{$this->description}\" for=\"{$this->name}\">".$this -> title.": {$star}</label> \n";
        $output .= "	<div class=\"button chooseFilesButton\"><span id=\"{$id}\"></span></div>";
        $output .= "	<div id=\"{$id}Inputs\" class=\"inputs\"></div>";
        
        $output .= "	<div class=\"form-upload-log\" id=\"form-upload-log-{$id}\"></div>";
        $output .= "</div> \n\n";
        
        return $output;
    }
    
    /**
     * Loads data, when form posted.
     *
     * @prefix string Form prefix.
     * @return array Loaded files.
     */
    function loadPostData($prefix)
    {
        // load
        $this -> files = $_POST[$prefix . $this -> name];
        if($this -> filesOriginal == array())
        {
            $this -> filesOriginal = $_POST[$prefix . $this -> name . "Original"];
        }
        
        return array($this -> name => $this -> filesOriginal);
    }
    
    /**
     * Validation before sending.
     */
    function validate()
    {
        $numberOfFiles = count($this -> files);
        
        // not enough files
        if($numberOfFiles < $this -> minFiles)
        {
            \Cyfy\Message :: set(Module :: t(102, array($this -> title, $this -> minFiles)), \Cyfy\Message::ERROR);
            return false;
        }
        
        // not too many files
        if($numberOfFiles > $this -> maxFiles)
        {
            \Cyfy\Message :: set(Module :: t(103, array($this -> title, $this -> maxFiles)), \Cyfy\Message::ERROR);
            return false;
        }
        return true;
    }
    
    /**
     * When submitted, uploads file from tmp dir to final destination.
     */
    function submit()
    {
        if(is_array($this -> files))
        {
            // custom prefix
            $dirname = ($this -> dirnameFromInput) ? $_POST[$this -> prefix . $this -> dirnameFromInput] . "/" : "";
            
            // files
            foreach($this -> files as $i => $file)
            {
                // custom name used?
                $path_info = pathinfo($this -> filesOriginal[$i]);
                $name = ($this -> customFilenames[$i]) ? $this -> customFilenames[$i] . "." . $path_info["extension"] : $this -> filesOriginal[$i];
                $this -> filesOriginal[$i] = $name;
                // save
                \Cyfy\Modules\jquerySWFUpload\Module :: moveUploadedFile($file, $this -> whereToUpload . $dirname . $name);				
                
            }
            return true;
        }
        return false;
    
    }

}